package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"xiwen/cache"
	"xiwen/models"
)

type XiwenController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Mag  string      `json:"mag"`
	Data interface{} `json:"data"`
}

func (c *XiwenController) Add() {
	name := c.GetString("name")
	age := c.GetString("age")
	address := c.GetString("address")
	var xinwen models.Xiwen
	xinwen.Name = name
	xinwen.Age = age
	xinwen.Address = address
	if name == "" || age == "" || address == "" {
		c.Data["json"] = JsonR{
			Code: 200,
			Mag:  "不能为空",
			Data: nil,
		}
	}
	err := xinwen.Add()

	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Mag:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	xinwens, _ := xinwen.List()
	jsonData, _ := json.Marshal(xinwens)
	cache.Rdb.Set(cache.Ctx, "key", jsonData, 0)
	c.Data["json"] = JsonR{
		Code: 200,
		Mag:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
func (c *XiwenController) Update() {
	id, _ := c.GetInt("id")
	if id < 1 {
		c.Data["json"] = JsonR{
			Code: 500,
			Mag:  "参数错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	name := c.GetString("name")
	age := c.GetString("age")
	address := c.GetString("address")
	var xinwen models.Xiwen
	xinwen.ID = uint(id)
	xinwen.Name = name
	xinwen.Age = age
	xinwen.Address = address
	if name == "" || age == "" || address == "" {
		c.Data["json"] = JsonR{
			Code: 200,
			Mag:  "不能为空",
			Data: nil,
		}
	}
	err := xinwen.Update()
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Mag:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	xinwens, _ := xinwen.List()
	jsonData, _ := json.Marshal(xinwens)
	cache.Rdb.Set(cache.Ctx, "key", jsonData, 0)
	c.Data["json"] = JsonR{
		Code: 200,
		Mag:  "修改成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
func (c *XiwenController) Del() {
	id, _ := c.GetInt("id")
	var xinwen models.Xiwen
	xinwen.ID = uint(id)
	if id < 1 {
		c.Data["json"] = JsonR{
			Code: 500,
			Mag:  "参数错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err := xinwen.Del()
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Mag:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	xinwens, _ := xinwen.List()
	jsonData, _ := json.Marshal(xinwens)
	cache.Rdb.Set(cache.Ctx, "key", jsonData, 0)
	c.Data["json"] = JsonR{
		Code: 200,
		Mag:  "删除成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
func (c *XiwenController) List() {
	ca := cache.Rdb.Get(cache.Ctx, "key").Val()
	var gg []*models.Xiwen
	if ca == "" {
		models.DB.Find(&gg)
		jsonData, _ := json.Marshal(gg)
		cache.Rdb.Set(cache.Ctx, "key_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(ca), &gg)
	}
	c.Data["json"] = JsonR{
		Code: 200,
		Mag:  "查询成功",
		Data: gg,
	}
	c.ServeJSON()
	return
}
